package com.wf.smartcomm.server.websocket;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.java_websocket.WebSocket;

public class ClientSocketPool {
	public static ConcurrentHashMap<WebSocket, String> clientPool = new ConcurrentHashMap<WebSocket, String>();
	
	public static void saveClient(WebSocket webSocket,String clientId){
		WebSocket oldSocket = getConnection(clientId);
		if (oldSocket != null) {
			clientPool.remove(oldSocket);
		}
		clientPool.put(webSocket, clientId);
	}
	
	public static void removeClient(WebSocket webSocket) {
		if (clientPool.containsKey(webSocket)) {
			clientPool.remove(webSocket);
		}
	}

	public static WebSocket getConnection(String clientId) {
		Set<WebSocket> webSockets = clientPool.keySet();
		for (WebSocket socket : webSockets) {
			if (clientPool.get(socket).equals(clientId)) {
				return socket;
			}
		}
		return null;
	}
	
	public static void sendMessage(String clientId,String message){
		WebSocket webSocket = getConnection(clientId);
		if (webSocket != null) {
			webSocket.send(message);
			System.out.println("find message send -----> "+clientId);
		}
	}
	
}	
